package com.datamation.swadeshi.view;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.adapter.NonProductiveRetailerAdapter;
import com.datamation.swadeshi.adapter.SalesExpenseDetailAdapter;
import com.datamation.swadeshi.adapter.SalesExpenseGridDetails;
import com.datamation.swadeshi.adapter.SetTitleAdapter;
import com.datamation.swadeshi.control.AddressAyncTask;
import com.datamation.swadeshi.control.DefaultTaskListener;
import com.datamation.swadeshi.control.GPSTracker;
import com.datamation.swadeshi.control.ReferenceNum;
import com.datamation.swadeshi.control.Toast;
import com.datamation.swadeshi.control.data.DebtorDS;
import com.datamation.swadeshi.control.data.ExpenseDS;
import com.datamation.swadeshi.control.data.FDayExpDetDS;
import com.datamation.swadeshi.control.data.FDayExpHedDS;
import com.datamation.swadeshi.control.data.SalRepDS;
import com.datamation.swadeshi.control.data.SharedPreferencesClass;
import com.datamation.swadeshi.model.Debtor;
import com.datamation.swadeshi.model.Expense;
import com.datamation.swadeshi.model.FDayExpDet;
import com.datamation.swadeshi.model.FDayExpHed;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.FeatureInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.SearchView.OnQueryTextListener;

public class FragmentSalesManagmentExpenseDetail extends Fragment implements OnClickListener {
	View view;
	EditText Txndate,Amount,ExpCode,Remark,RefNo;
	ArrayList<Debtor> list;
	ArrayList<Expense> list2;
	Button btnAdd;
	ListView lv_invent_load;
	ReferenceNum referenceNum;
	ArrayList<FDayExpDet> loadlist;
	GPSTracker gpsTracker;
	Toast  toast;
	int seqno=0;
	public static SharedPreferences localSP;
	public static final String SETTINGS = "SETTINGS";
	public static String DebCODE,RESULT;
	
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.expense_hed, container, false);
		setHasOptionsMenu(true);
		MainActivity activity =(MainActivity) getActivity();
		 
		seqno=0;
		
		SetTitleAdapter adapterUnload =new SetTitleAdapter();
		adapterUnload.createCutomActionBarTitle("Expens Detail", getActivity());

		getActivity().getActionBar().removeAllTabs();
		getActivity().getActionBar().setNavigationMode(0);
		
		RefNo = (EditText)view.findViewById(R.id._refNo);
		Txndate = (EditText)view.findViewById(R.id._date);
		Remark = (EditText)view.findViewById(R.id._remrk);
		Amount = (EditText)view.findViewById(R.id._amount);
		ExpCode = (EditText)view.findViewById(R.id._expcode);
		Button ReSearch = (Button)view.findViewById(R.id.reason_search);
		referenceNum = new  ReferenceNum(getActivity());
		RefNo.setText(referenceNum.getCurrentRefNo(getResources().getString(R.string.ExpenseNumVal)));
		btnAdd = (Button)view.findViewById(R.id.btn_add);
		btnAdd.setOnClickListener(this);
		gpsTracker=new GPSTracker(getActivity());
		toast = new Toast();
		fatchData();
		localSP = activity.getSharedPreferences(SETTINGS,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
		
//		CusSearch.setOnClickListener(new View.OnClickListener() 
//		{
//			
//			@Override
//			public void onClick(View v) 
//			{
//				// TODO Auto-generated method stub
//				switch (v.getId()) 
//				{
//				case R.id.btn_retail_search:
//					DebDetailsDialogbox("");
//					break;
//				
//				default:
//					break;
//				}
//				
//			}
//		});
		ReSearch.setOnClickListener(new View.OnClickListener() 
		{
			
			@Override
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				switch (v.getId()) 
				{
				case R.id.reason_search:
					ReasonDetailsDialogbox("");
					break;
				
				default:
					break;
				}
				
			}
		});
		lv_invent_load.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				// TODO Auto-generated method stub
				FDayExpDet fexpdet = loadlist.get(position);
				//toast.createToastMessage(fnondet.getNONPRDDET_ID().toString(), getActivity());
				
				deleteOrderDialog(getActivity(), fexpdet.getEXPDET_REFNO().toString(),fexpdet.getEXPDET_EXPCODE().toString());
				toast.createToastMessage(fexpdet.getEXPDET_ID().toString(), getActivity());
				return false;
			}
		});

		
		
		
		lv_invent_load.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view2,int position, long id) 
			{
				
				
				clearTextFields();
				DebtorDS dsg=new DebtorDS(getActivity());
				btnAdd.setText("Update");
			
		
			FDayExpDet fnondet = loadlist.get(position);
			Amount.setText(fnondet.getEXPDET_AMOUNT());
			ExpCode.setText(fnondet.getEXPDET_EXPCODE());

	
			}
		});
		
//		new AddressAyncTask(getActivity(),this).execute();
//		try {
//			if(activity.selectednonHed.getNONPRDHED_ADDRESS() == null)
//			{
//				 
//			}
//			else
//			{
//				Log.v("GPS address", activity.selectednonHed.getNONPRDHED_ADDRESS().toString());
//			}
//		}catch (Exception e){
//			Log.v("Exception", e.toString());
//		}
		currentDate();
		return view;
	}
	
	private void currentDate() {
		// TODO Auto-generated method stub
		//current date and time 
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date date = new Date();
				Txndate.setText(dateFormat.format(date));
				//deliveryDate.setText(dateFormat.format(date));
	}

	
	public void DebDetailsDialogbox(String searchword)
	{		
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.nonprod_retailer_search);
		final SearchView search = (SearchView) dialog.findViewById(R.id.rt_search);
		final ListView locList=(ListView) dialog.findViewById(R.id.rt_product_items); 
		dialog.setCancelable(true);
		
		DebtorDS dsg=new DebtorDS(getActivity());
		list= dsg.getAllCustomers();
	   	locList.clearTextFilter();
		locList.setAdapter(new NonProductiveRetailerAdapter(getActivity(),list));
		locList.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) 
			{
				Amount.setText(list.get(position).getFDEBTOR_NAME());
				DebCODE = list.get(position).getFDEBTOR_CODE();
				dialog.dismiss();
			}
		});
		
			
		search.setOnQueryTextListener(new OnQueryTextListener() 
		{
			
			@Override
			public boolean onQueryTextSubmit(String query) 
			{
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) 
			{
				DebtorDS locds =new DebtorDS(getActivity());
				locList.clearTextFilter();
				list= locds.getDebDetails(newText);
				locList.setAdapter(new NonProductiveRetailerAdapter(getActivity(),list));
				return false;
			}
		});				
		dialog.show();
	}
	
	public void ReasonDetailsDialogbox(String searchword)
	{		
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.nonprod_retailer_search);
		final SearchView search = (SearchView) dialog.findViewById(R.id.rt_search);
		final ListView locList=(ListView) dialog.findViewById(R.id.rt_product_items); 
		dialog.setCancelable(true);
		
		ExpenseDS dsg=new ExpenseDS(getActivity());
		list2= dsg.getAllExpense("GCR001");
	   	locList.clearTextFilter();
		locList.setAdapter(new SalesExpenseDetailAdapter(getActivity(),list2));
		locList.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) 
			{
				ExpCode.setText(list2.get(position).getFEXPENSE_NAME());

			
				dialog.dismiss();
			}
		});
		
			
		search.setOnQueryTextListener(new OnQueryTextListener() 
		{
			
			@Override
			public boolean onQueryTextSubmit(String query) 
			{
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) 
			{
				ExpenseDS locds =new ExpenseDS(getActivity());
				locList.clearTextFilter();
				list2= locds.getExpDetails(newText);
				locList.setAdapter(new SalesExpenseDetailAdapter(getActivity(),list2));
				return false;
			}
		});				
		dialog.show();
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
		for(int i = 0; i < menu.size(); ++i)
		{
			menu.removeItem(menu.getItem(i).getItemId());
		}
		
		inflater.inflate(R.menu.frag_per_sales_summary, menu);

		super.onCreateOptionsMenu(menu, inflater);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.action_pre_sale_undo)
		{
			undoEditingData(getActivity());
		    
		}
		if(item.getItemId() == R.id.action_pre_sales_save)
		{
			saveSummaryDialog(getActivity());

			
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) 
		{
		case R.id.btn_add:
			btnAdd.setText("Add");
			if (Amount.length()!=0 && ExpCode.length()!=0) 
			{
				FDayExpDetDS chk=new FDayExpDetDS(getActivity());
				
//				if (!chk.getDuplicate(DebCODE.toString(),RefNo.getText().toString()).equals(DebCODE.toString())) 
//				{
				FDayExpDet expdet=new FDayExpDet();
				FDayExpDetDS expDetDS=new FDayExpDetDS(getActivity());
				ArrayList<FDayExpDet> ExpDetList=new ArrayList<FDayExpDet>();
				SalRepDS repDS=new SalRepDS(getActivity());
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date date = new Date();

				try {
				seqno++;
					
				FDayExpDetDS deb =new FDayExpDetDS(getActivity());
				expdet.setEXPDET_REFNO(RefNo.getText()+"");
				expdet.setEXPDET_EXPCODE(ExpCode.getText()+"");
				expdet.setEXPDET_TXNDATE(dateFormat.format(date));
				expdet.setEXPDET_AMOUNT(Amount.getText()+"");
				expdet.setEXPDET_SEQNO(seqno+"");
				
				ExpDetList.add(expdet);
				
				if(expDetDS.createOrUpdateExpenseDet(ExpDetList)>0)
				{
					clearTextFields();
					toast.createToastMessage("Added successfully", getActivity());
					//actionBar.removeAllTabs();
					fatchData();

				}else {
					toast.createToastMessage("Added Not successfully", getActivity());
				}
				
				} catch (Exception e) {
					// TODO: handle exception
				}
//				}
//				else {
//					toast.createToastMessage("This Item Already added", getActivity());
//					clearTextFields();
//				}
				
			}else {
				toast.createToastMessage("Added Not successfully", getActivity());
			}
			

			break;
		
		default:
			break;
		}
	}
	public void fatchData()
	{
		try {
			MainActivity activity =(MainActivity) getActivity();
			lv_invent_load = (ListView) view.findViewById(R.id.lv_loading_sum);
			//lv_invent_load.clearTextFilter();
			FDayExpDetDS detDS = new FDayExpDetDS(getActivity());
			loadlist = detDS.getAllExpDetails(referenceNum.getCurrentRefNo(getResources().getString(R.string.ExpenseNumVal)));
			
			lv_invent_load.setAdapter(new SalesExpenseGridDetails(getActivity(), loadlist));
		}catch (NullPointerException e){
			Log.v("Loading Error", e.toString());
		}
	}
	public void clearTextFields() 
	{
		Remark.setText("");
		Amount.setText("");
		ExpCode.setText("");
		DebCODE = "";

		
	}
	private void saveSummaryDialog(final Context context){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure you want to save this entry?");
		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
				{
							public void onClick(DialogInterface dialog, int id) 
							{
								
								FDayExpDetDS deb =new FDayExpDetDS(getActivity());
								if (deb.getAllExpDetails(RefNo.getText()+"").size()>0) 
								{
								//new AddressAyncTask(getActivity(),this).execute();
									
								FDayExpHed exphed=new FDayExpHed();
								ArrayList<FDayExpHed> ExpHedList=new ArrayList<FDayExpHed>();
								FDayExpHedDS expHedDS=new FDayExpHedDS(getActivity());
								GPSTracker gpsTracker=new GPSTracker(getActivity());
								SalRepDS repDS=new SalRepDS(getActivity());
								DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
								Date date = new Date();
								
								String refno = RefNo.getText().toString();
								exphed.setEXPHED_REFNO(RefNo.getText()+"");
								exphed.setEXPHED_REPCODE(repDS.getCurrentRepCode());
								exphed.setEXPHED_TXNDATE(dateFormat.format(date));
								exphed.setEXPHED_REMARK(Remark.getText()+"");
								exphed.setEXPHED_ADDDATE(dateFormat.format(date));
								exphed.setEXPHED_ADDMACH(localSP.getString("MAC_Address", "No MAC Address").toString());
								exphed.setEXPHED_ADDUSER(repDS.getCurrentRepCode());
								exphed.setEXPHED_DEALCODE("");
								exphed.setEXPHED_IS_SYNCED("0");
								exphed.setEXPHED_LATITUDE(gpsTracker.getLatitude()+"");
								exphed.setEXPHED_LONGITUDE(gpsTracker.getLongitude()+"");
								exphed.setEXPHED_ADDRESS(localSP.getString("GPS_Address", "").toString());
								exphed.setEXPHED_TOTAMT(deb.getTotalExpenseSumReturns(refno));
								ExpHedList.add(exphed);
								
								if (expHedDS.createOrUpdateNonPrdHed(ExpHedList)>0) 
								{
									referenceNum.nNumValueInsertOrUpdate(getResources().getString(R.string.ExpenseNumVal));
									FragmentTransaction transaction = getFragmentManager().beginTransaction();
									transaction.replace(R.id.frame_container, new FragmentSalesManagmentExpenseMain());
									transaction.addToBackStack(null);
									transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
									transaction.commit();
								}
								
								}else {
									toast.createToastMessage("No Data For Save", getActivity());
								}
								

								}
						})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
						    	dialog.cancel();
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	private void deleteOrderDialog(final Context context,final String refno, final String expcode){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure you want to delete this entry?");
		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
				{
							public void onClick(DialogInterface dialog, int id) 
							{
							
								
								int count =new FDayExpDetDS(context).DeleteRec(refno,expcode);					
								if(count >0)
								{
									toast.createToastMessage("Deleted successfully", getActivity());
									fatchData();
									clearTextFields();
								}
							}
						})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								dialog.cancel();
								
								
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	
	private void undoEditingData(final Context context){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure you want to Undo this entry?");
		final FDayExpHedDS expHED =new FDayExpHedDS(getActivity());
		final FDayExpDetDS expDET=new FDayExpDetDS(getActivity());
		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								
								ReferenceNum referenceNum =new  ReferenceNum(getActivity());
								MainActivity activity =(MainActivity) getActivity(); 
								
								//delete data
								try {
									expHED.undoOrdHedByID(referenceNum.getCurrentRefNo(getResources().getString(R.string.ExpenseNumVal))); 
								}catch(Exception e){
									
								}
								try {
									expDET.OrdDetByID(referenceNum.getCurrentRefNo(getResources().getString(R.string.ExpenseNumVal))); 
								}catch(Exception e){
									
								}
								FragmentTransaction transaction = getFragmentManager().beginTransaction();
								transaction.replace(R.id.frame_container, new FragmentSalesManagmentExpenseMain());
								transaction.addToBackStack(null);
								transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
								transaction.commit();
								toast.createToastMessage("Undo Success", getActivity());
								
							}
					})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								
								dialog.cancel();
								
								
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	
	public void onTaskCompleted(String result) {
		// TODO Auto-generated method stub
		try {
			if(!result.equals("") || !result.equals("No Address"))
			{
				
				MainActivity activity =(MainActivity) getActivity();
				
					//if(activity.selectednonHed.getNONPRDHED_ADDRESS() == null){
						toast.createToastMessage(result, getActivity());
						SharedPreferencesClass.setLocalSharedPreference(getActivity(),"GPS_Address",result);
						activity.selectedexpHed.setEXPHED_ADDRESS(result);
				
				
			}
		}catch (Exception e){
			Log.v("Exception Selected OrdHed ", e.toString());
		}
	}

}
